// pages/petCardAdd/petCardAdd.js
const qiniuUploader = require("../../utils/qiniuUploader");
var that;
Page({

  /**
   * 页面的初始数据
   */
  data: {

    title:"宠卡信息",
    images:"",
    height:"",
    sex:"",
    date:"",
    PetTypeList:[],
    imgname:"",
    breed:"",
    weight:null,
    name:"",
    time:"",

    isSee:1,
    item:"",
    config:"",
    // imageURL:{},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    

    that.data.isSee=options.isSee
    console.log(that.data.isSee)
    if (options.isSee == 1){
      /**
       * 添加
       */
    }else{
      /**
       * 修改查看
       */
      var item = JSON.parse(options.item) 
       var breed = new Object();
      breed.pId = item.ftypeId,
        breed.id = item.stypeId,
        breed.name = item.typeName,
      that.setData({
        item:item,
        images: item.photoUrl,
        sex: (item.gender == 1 ? "公" : "母"),
        weight: item.weight,
        date: that.formatDateTime(item.birthday/1000),
        time: item.birthday,
        breed:breed,
        name:item.name,

      });
      console.log(item)
    }
    
    wx.setNavigationBarTitle({
      title: options.isSee == 1 ? "添加宠卡":that.data.title//页面标题为路由参数
    })
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          height: res.windowHeight - res.windowWidth / 750 * 40
        })
        
      }
    }) 


    that.data.config = {
      useCdnDomain: true
    }

  },


  formatDateTime:function(timeStamp) { 

    var date = new Date();

    date.setTime(timeStamp * 1000);

    var y = date.getFullYear();    

    var m = date.getMonth() + 1;    

    m = m < 10 ? ('0' + m) : m;    

    var d = date.getDate();    

    d = d < 10 ? ('0' + d) : d;    

    return y + '-' + m + '-' + d;    

  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },


 /**
   * 头像
   */
  head_portrait:function(){
    // 选择图片
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths[0];
        console.log(tempFilePaths);
        that.setData({
          images: tempFilePaths
        });
        if(that.data.isSee == 2){
          var weibu = tempFilePaths.split(".")[tempFilePaths.split(".").length - 1]

          var weibu = that.data.imgname.split(".")[that.data.imgname.split(".").length - 1]
          var name = "img" + new Date().getTime() + "." + weibu;
          that.setData({ imgname: name })
          wx.request({
            url: getApp().globalData.urls + '/wxgz/media/getUploadToken',
            data: {
              fileName: name
            },

            method: "POST",
            header: {
              'content-type': 'application/x-www-form-urlencoded' // post:application/x-www-form-urlencoded,get:application/json
            },
            success: function (res) {
              var e = res;
              console.log(e.data)
              if (e.data.code == 200) {

                qiniuUploader.upload(that.data.images, (res) => {

                  that.setData({
                    'imageURL': res.imageURL,
                  });
                  that.savePetIcon();
                }, (error) => {

                  console.log('error: ' + error);
                }, {

                    region: 'ECN',
                    key: that.data.imgname,
                    uptoken: e.data.data, // 由其他程序生成七牛 uptoken
                    // uptokenURL: 'UpTokenURL.com/uptoken', // 从指定 url 通过 HTTP GET 获取 uptoken，返回的格式必须是 json 且包含 uptoken 字段，例如： {"uptoken": "[yourTokenString]"}
                    // uptokenFunc: function () { return e.data.data; }
                  }, (res) => {
                    console.log('上传进度', res.progress)
                    console.log('已经上传的数据长度', res.totalBytesSent)
                    console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)

                  });
              }



            }
          })

        }
      }
    })
  },

  /**
   * 昵称
   */
  name:function(e){
    that.setData({ name: e.detail.value });
  },


   /**
   * 性别
   */
  sex:function(){
    wx.showActionSheet({
      itemList: ['公', '母'],
      success: function (res) {
        that.setData({
          sex: (res.tapIndex == 0? "公":"母")
       })
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },
  /**
   * 生日
   */
  bindDateChange: function (e) {
    var str = e.detail.value.replace(/-/g, '/'); // 将-替换成/，因为下面这个构造函数只支持/分隔的日期字符串

    var date = new Date(str); // 构造一个日期型数据，值为传入的字符串
    var time = date.getTime();
    this.setData({
      date: e.detail.value,
      time: date.getTime()
    })
    console.log(e.detail.value)

    console.log(date.getTime())
  },
  /**
   * 品种选择
   */
  breed:function(){
    wx.navigateTo({
      url: '../petCardbreed/petCardbreed1/petCardbreed1'
    })
  },
  /**
   * 体重
   */
  weight:function(e){
    that.setData({ weight: e.detail.value });

  },


tjxx:function(){
  if (that.data.isSee == 2){
    
    that.savePet();
    return;
  }
  var weibu = that.data.imgname.split(".")[that.data.imgname.split(".").length - 1]
  var name = "img" + new Date().getTime() + "." + weibu;
  that.setData({ imgname: name})
  wx.request({
    url: getApp().globalData.urls +  '/wxgz/media/getUploadToken',
    data: {
      fileName: name
    },
    
    method: "POST",
    header: {
      'content-type': 'application/x-www-form-urlencoded' // post:application/x-www-form-urlencoded,get:application/json
    },
    success: function (res){
      var e = res;
      console.log(e.data)
      if(e.data.code == 200){

        qiniuUploader.upload(that.data.images, (res) => {
          
          that.setData({
            'imageURL': res.imageURL,
          });
          that.savePet();
        }, (error) => {
        
          console.log('error: ' + error);
        }, {
            
            region: 'ECN',
            key: that.data.imgname,
            uptoken: e.data.data, // 由其他程序生成七牛 uptoken
            // uptokenURL: 'UpTokenURL.com/uptoken', // 从指定 url 通过 HTTP GET 获取 uptoken，返回的格式必须是 json 且包含 uptoken 字段，例如： {"uptoken": "[yourTokenString]"}
            // uptokenFunc: function () { return e.data.data; }
          }, (res) => {
            console.log('上传进度', res.progress)
            console.log('已经上传的数据长度', res.totalBytesSent)
            console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
            
          });
      }

      

    }
  })
},

  savePet:function(){
    wx.request({
        
      url: getApp().globalData.urls + (that.data.isSee == 1?'/wxgz/pet/savePet':"/wxgz/pet/updatePet"),
      data: that.data.isSee == 1 ?{
        name: that.data.name,
        token:wx.getStorageSync("token"),
        fileName: that.data.imgname,
        ftypeId: that.data.breed.pId,
        stypeId: that.data.breed.id,
        typeName: that.data.breed.name,
        gender: that.data.sex == "公"? 1 : 2,
        weight: that.data.weight,
        birthday:that.data.time,
      }:{
          name: that.data.name,
          token: wx.getStorageSync("token"),
          ftypeId: that.data.breed.pId,
          stypeId: that.data.breed.id,
          typeName: that.data.breed.name,
          gender: that.data.sex == "公" ? 1 : 2,
          weight: that.data.weight,
          birthday: that.data.time,
          petId:that.data.item.id,
      },

      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded' // post:application/x-www-form-urlencoded,get:application/json
      },
      success: function (res) {
      
        console.log(res.data)
        if(res.data.code == 200){
          wx.showToast({
            title: that.data.isSee == 1 ?'宠卡添加成功':"宠卡修改成功",
          })
          wx.navigateBack()
        }else{

        }
      },
      fail:function(e){
        wx.showToast({
          title: '网络开小差了',
        })
      
      }
    })
  },

  savePetIcon:function(e){
    wx.request({
      url: getApp().globalData.urls + "/wxgz/pet/savePetIcon",
      data:{
        petId: that.data.item.id,
        token: wx.getStorageSync("token"),
        fileName: that.data.imgname,
      },
      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded' // post:application/x-www-form-urlencoded,get:application/json
      },
      success: function (res) {

        console.log(res.data)
        if (res.data.code == 200) {
          wx.showToast({
            title: "头像修改成功",
          })
        
        } else {

        }
      },
      fail: function (e) {
        wx.showToast({
          title: '网络开小差了',
        })

      }
    })
  }
})